import { service, crudParamsSerializer } from '@/utils/request'
import { CreateQueryParams } from '@nestjsx/crud-request'
import { Song } from './song.dto'
import { CrudPaginatedRes } from '..'
import * as _ from 'lodash'

export const defaultSongData: Partial<Song> = {
  title: '',
  duration: 0,
  visible: true,
  belongsToArtists: []
}

export function getSongs (params?: CreateQueryParams) {
  return service.get<Song[] | CrudPaginatedRes<Song>>(
    '/resources/songs',
    {
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}

export function getSongById (id: number | string, params?: CreateQueryParams) {
  return service.get<Song>(
     `/resources/songs/${id}`,
     {
       params,
       paramsSerializer: crudParamsSerializer
     }
  )
}

export function checkFavSong (id: number | string) {
  return service.request({
    url: `/resources/songs/${id}/fav`,
    method: 'get'
  })
}

export function setFavSong (id: number | string) {
  return service.request({
    url: `/resources/songs/${id}/fav`,
    method: 'post'
  })
}

export function removeFavSong (id: number | string) {
  return service.request({
    url: `/resources/songs/${id}/fav`,
    method: 'delete'
  })
}

export function createSong (dto: Partial<Song>, params?: CreateQueryParams) {
  const data = new FormData()
  _.forIn(dto, (value, key) => {
    if (key !== 'id' && value) {
      if (typeof value === 'string' || typeof value === 'number') {
        data.append(key, value.toString())
      } else if (value instanceof Blob) {
        data.append(key, value)
      } else if (value instanceof Date) {
        data.append(key, value.toISOString())
      } else {
        data.append(key, JSON.stringify(value))
      }
    }
  })
  return service.post<Song>(
    '/resources/songs',
    data,
    {
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}

export function updateSong (id: number | string, dto: Partial<Song>, params?: CreateQueryParams) {
  const data = new FormData()
  _.forIn(dto, (value, key) => {
    if (key !== 'id' && value) {
      if (typeof value === 'string' || typeof value === 'number') {
        data.append(key, value.toString())
      } else if (value instanceof Blob) {
        data.append(key, value)
      } else if (value instanceof Date) {
        data.append(key, value.toISOString())
      } else {
        data.append(key, JSON.stringify(value))
      }
    }
  })
  return service.patch<Song>(
     `/resources/songs/${id}`,
     data, {
       params,
       paramsSerializer: crudParamsSerializer
     }
  )
}
